import React, { useEffect, useState } from 'react'
import {
    Table,
    Space,
    Modal,
    Form,
    Input,
    Select,
    DatePicker,
    TimePicker,
    message,
    Spin,
} from 'antd';
import {coupon} from '../../request'
import moment from 'moment';

import './discount.moudles..css'

function onChange(time, timeString) {
    console.log(time, timeString);
}

export default (props) => {
    const [coupons,setCoupon] = useState(null)   //获取发布所有的优惠券
    const [allData, setAllData] = useState([])    //整理后端发布优惠券的内容，渲染在页面上
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [muban, setMuban] = useState([])   //获取模板优惠券,将title渲染在下拉选择框中供用户模板选择
    const [complieData, setCompileData] = useState(null)


    const [form] = Form.useForm();

    useEffect(()=>{
        getMsg();

    },[])

    useEffect(()=>{
        if(coupons){
            setAllData(coupons.map((item, index)=>{
                const {juanFa_id, juanFa_boo, disJuan_use, disJuan_money, disJuan_time, juanFa_time, juanFa_num,disJuan_title } = item
                return {
                    key : juanFa_id,
                    juanFa_id, juanFa_time, juanFa_num, disJuan_title,
                    juanFa_boo : juanFa_boo === 0 ? '发行中': juanFa_boo === 1 ? '已过期' : '已下架',
                    disJuan_time : disJuan_time + '天',
                    disJuan_name : '满' + disJuan_use + '减' + disJuan_money
                }
            }))
        }


    },[coupons])

    //请求数据
    const getMsg = async() =>{
        const {data:res} = await coupon.getCoupon()
        if(res.code === 200){

            setCoupon(res.data)
        }else{
            console.log('请求数据失败');
        }
    }

    const columns = [
        {
            title: '优惠券id',
            dataIndex: 'juanFa_id',
            key: 'juanFa_id',
            render: text => <a>{text}</a>,
        },
        {
            title: '优惠券标题',
            dataIndex: 'disJuan_title',
            key: 'disJuan_title',
            render: text => <a>{text}</a>,
        },

        {
            title: '优惠券状态',
            dataIndex: 'juanFa_boo',
            key: 'juanFa_boo',
        },
        {
            title: '优惠券名称',
            dataIndex: 'disJuan_name',
            key: 'disJuan_name',
        },
        {
            title: '优惠券有效期',
            dataIndex: 'disJuan_time',
            key: 'disJuan_time',
        },
        {
            title: '优惠券结束时间',
            dataIndex: 'juanFa_time',
            key: 'juanFa_time',
        },
        {
            title: '优惠券发布数量',
            dataIndex: 'juanFa_num',
            key: 'juanFa_num',
        },
        {
            title: '操作',
            key: 'action',
            render: (record) => (

                <Space size="middle">
                    {/*<a onClick={()=>{ compile(record.juanFa_id) }}>编辑 {record.name}</a>*/}
                    <a onClick={()=> {couponDelete(record.juanFa_id)}}>删除</a>
                </Space>
            ),
        },
    ];

    //编辑优惠券：正在发行中的优惠券若没有到时间则可以进行重新编辑，其他已经在发布或者下架的都不可以再重新编辑
    const compile = async (couponId)=>{

    }

    //删除数据
    const couponDelete = async(couponId) =>{

        const {data:res} = await coupon.deleteCoupon(couponId)
        if(res.code === 200){
            let newCoupon = coupons.filter(item=>item.juanFa_id!==couponId)
            setCoupon(newCoupon)
        }else{
            message.error('无法删除数据');
        }
    }


    //model弹框
    const showModal = async () => {


        //向后端请求模板样式title数据
        const {data: res} = await coupon.getDisjuan()
        if (res.code === 200) {

            setMuban(res.data)
        } else {
            console.log('请求数据失败');
        }

        setIsModalVisible(true);



    };
    const handleOk = async (value) => {

        let {disJuan_id, juanFa_date, juanFa_num, juanFa_time} = form.getFieldsValue();
        juanFa_date =  moment( juanFa_date ).format('YYYY-MM-DD');

        juanFa_time = moment( juanFa_time ).format('HH:mm:ss')

        juanFa_time = juanFa_date + ' '+ juanFa_time;

        console.log(disJuan_id, juanFa_num, juanFa_time);

        //将新增的发布优惠券发送到后端
        const {data: res} = await coupon.addjuanfa(disJuan_id, juanFa_num, juanFa_time)
        if (res.code === 200) {
            success()

        } else {
            error()
        }


    };

    //数据保存成功弹窗提示框
    const success = () => {
        message.success('发布优惠券成功');
    };

    //数据保存失败弹窗提示框
    const error = () => {
        message.error('网络拥挤，发布优惠券失败，请稍后发布');
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };



    //禁选时间
    const disabledDate=(current) =>{
        const disabledEndDay = new Date();
        return current < disabledEndDay;
    }



    //添加提交
    const onFinish = async (values) =>{
        console.log(values )

    }



    return(

        allData.length === 0 ? (<div className={'loading'}> <Spin size={'large'} /></div>)
            :
        <div className={'discount'}>

           <header>
               <h3 className={'title'}>优惠券列表</h3>
               <div className={'tips'}>优惠券只能抵扣商品金额，不能抵扣运费</div>
           </header>

            <section>
                <button type={'button'} className={"add"} onClick={showModal}>+ 新增优惠券</button>
                <Table columns={columns} dataSource={allData} style={{width:1200}}/>

            </section>


            <Modal title="发布优惠券" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel} getContainer={false} >
                {/*新增发布优惠券*/}
                <Form
                    labelCol={{
                        span: 6,
                    }}
                    wrapperCol={{
                        span: 14,
                    }}
                    layout="horizontal"
                    onFinish={onFinish}

                    initialValues={{
                        OpenValue:moment('00:00:00', 'HH:mm:ss')

                    }}

                    form={form}

                >


                    <Form.Item label="选择优惠券模板" name='disJuan_id' rules={
                        [
                            {
                                required:true,
                                message:'请选择一个优惠券模板',
                            }
                        ]
                    }>
                        {
                            !muban ? '':
                                (
                                    <Select>
                                        {
                                            muban.map((item, index)=>{
                                                return <Select.Option value={item.disJuan_id} key={item.disJuan_id}> {item.disJuan_title} </Select.Option>
                                            })
                                        }


                                    </Select>
                                )
                        }

                    </Form.Item>
                    <Form.Item label="发布数量" name='juanFa_num' rules={
                        [
                            {
                                required:true,
                                message:'请填入发布的天数，注意是整数格式',
                                pattern:/\d/
                            }
                        ]
                    }>
                        <Input />
                    </Form.Item>


                    <Form.Item label="发布时间"  name={'juanFa_date'} rules={
                        [
                            {
                                required:true,
                                message:'请选择发布的日期'
                            }
                        ]
                    }>
                        <DatePicker disabledDate={disabledDate} />
                    </Form.Item>
                    <Form.Item label="发布时间"  name={'juanFa_time'} rules={
                        [
                            {
                                required:true,
                                message:'请选择发布的时间'
                            }
                        ]
                    }>
                        <TimePicker onChange={onChange} name={'OpenValue'}  />

                    </Form.Item>


                </Form>
            </Modal>



        </div>
    );
};

